package fun.codedesign.principle.advice151.a108;

import org.junit.Test;

import fun.codedesign.principle.advice151.Notice;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/**
 * 模板方法中的反射应用 <br>
 * <pre>
 * </pre>
 *
 * @author zengjian
 * @create 2018-07-08 15:31
 * @since 1.0.0
 */
@Notice("反射在模板方法中的应用")
public class TemplateReflection {

    @Test
    public void test108() throws Exception {
        Mode m = new Impl1();
        m.initData();
    }
}

abstract class Mode {

    public final void initData() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        Method[] methods = getClass().getDeclaredMethods();
        for (Method method : methods) {
            if (isInitDataMethod(method)) {
                method.invoke(this);
            }
        }
    }

    private boolean isInitDataMethod(Method method) {
        if (method.getName().startsWith("init")
                && Modifier.isPublic(method.getModifiers())
                && method.getReturnType().equals(Void.TYPE)
                && !method.isVarArgs()
                && !Modifier.isAbstract(method.getModifiers())) {
            return true;
        }
        return false;
    }
}

class Impl1 extends Mode {

    public void initAccount() {
        System.out.println("初始化账户");
    }

    public void initPassword() {
        System.out.println("初始化密码");
    }
}

class Impl2 extends Mode {

}
